
// Additional JS functions here
window.fbAsyncInit = function() 
{
	FB.init({		appId		: '184566795035694',							// App ID
				channelUrl	: '//tel-o-fun.cloudfoundry.com/channel.html',	 // Channel File
				status		: true,									 // check login status
				cookie		: true,									// enable cookies to allow the server to access the session
				xfbml		: true									// parse XFBML
			});
	FB.Event.subscribe('auth.authResponseChange',  onAuthResponseChange);
};

// Load the SDK asynchronously
(function(d) 
{
	var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
	if (d.getElementById(id)) 
	{
		return;
	}
	js			= d.createElement('script');
	js.id		= id;
	js.async		= true;
	js.src		= "//connect.facebook.net/en_US/all.js";
	ref.parentNode.insertBefore(js, ref);
}(document));

function checkSSL()
{
	if(document.URL.match("https://") === null)
	{
		window.location.replace(document.URL.replace("http://", "https://"));
	}
}

function onAuthResponseChange(response)
{
	var e = document.getElementById("welcomeUser");

	if (e !== null)
	{
		if (response.status === 'connected') 
		{
			FB.api(	'/me', 
					function(response)
					{
						e.innerHTML = 'Welcome ' + response.name + '!';
					});
		} 
		else
		{
			e.innerHTML = 'Welcome!';
		}
	}
}

function DoNothingResponse(response) {}

function AsyncPostedResponse(response)
{
	alert("Done !!!");
}

function PostToFacebook(bConnected)
{
	if(bConnected)
	{
		FB.api(	'me/feed',
				'post',
				{
					picture		: 'http://tel-o-fun.cloudfoundry.com/images/telofan.jpeg',
					message		: "Rent a Tel-O-fun bike!"
				},
				AsyncPostedResponse);
	}
}

function LoginToFacebook(AsyncCB)
{
	if(!bIsFacebookConnected())
	{
		FB.login( function(response)
				{
					AsyncCB(response.authResponse);
				},
				{scope: 'publish_stream,publish_actions'});
	}
}

function bIsFacebookConnected()
{
	var authResponse = FB.getAuthResponse();
	return ((typeof authResponse !== 'undefined') && (null !== authResponse));
}

function onPostToFacebookClick()
{
	if(bIsFacebookConnected())
	{
		PostToFacebook(true);
	}
	else
	{
		LoginToFacebook(PostToFacebook);
	}
}

function onLogoutFacebookClick()
{
	if(bIsFacebookConnected())
	{
		FB.logout(DoNothingResponse);
	}
}